import { useEffect, useState } from "react"
import styles from "./article.module.scss"
import request from "../../utils/request"
import logo from "../../../public/logo.svg"
import { useNavigate, useLocation } from "react-router-dom"
import { marked } from "marked"

// 定义ArticleData接口
interface ArticleData {
  id: number
  title: string
  content: string
  create_time: string
  keywords: string
  views: number
}

// 获取文章详情的异步函数
const getArticleDetails = async (
  id: number
): Promise<ArticleData | undefined> => {
  const { data: res } = await request.post("/article/details", { id })
  if (res.status !== 200) return undefined
  return res.data as ArticleData
}

// Article组件
const Article: React.FC = () => {
  const [articleData, setArticleData] = useState<ArticleData | null>(null)
  const [outline, setOutline] = useState<{ title: string; id: string }[]>([])

  // 生成大纲
  const generateOutline = async (content: string) => {
    // 先将Markdown转换为HTML
    const htmlContent = await marked(content) // 使用await等待marked函数完成

    const headings: { title: string; id: string }[] = []
    const regex = /<h([1-6])[^>]*>(.*?)<\/h\1>/g
    let match: RegExpExecArray | null
    while ((match = regex.exec(htmlContent as any)) !== null) {
      const level = match[1] // 获取标题级别
      const text = match[2] // 获取标题文本
      const id = `heading-${headings.length}` // 为每个标题生成唯一id
      headings.push({ title: text, id })

      // 使用正则替换，给每个标题添加 id 属性
      htmlContent.replace(
        new RegExp(`<h${level}[^>]*>(${text})</h${level}>`),
        `<h${level} id="${id}">${text}</h${level}>`
      )
    }

    // 打印生成的大纲，帮助调试
    setOutline(headings)
  }
  // 获取当前路径的完整信息
  const location = useLocation()

  useEffect(() => {
    const fetchData = async () => {
      // 解析查询字符串中的参数
      const queryParams = new URLSearchParams(location.search)
      // const queryParams = new URLSearchParams(window.location.search)
      const idParam = queryParams.get("id")
      let articleID: number | undefined
      if (idParam) {
        const parsedId = parseInt(idParam)
        if (!isNaN(parsedId)) {
          articleID = parsedId
        }
      }
      if (articleID !== undefined) {
        const data = await getArticleDetails(articleID)
        if (data) {
          setArticleData(data)
          document.title = data.title
          await generateOutline(data.content) // 使用await等待generateOutline函数完成
        }
      }
    }
    fetchData()
  }, [])

  const navigate = useNavigate()
  const gobackHome = () => {
    navigate("/")
    document.title = "鼠觅奇物"
  }

  // 滚动到对应位置
  const scrollToAnchor = (id: string) => {
    const element = document.getElementById(id)
    if (element) {
      element.scrollIntoView({ behavior: "smooth", block: "start" })
    }
  }

  return (
    <article className={styles.article}>
      {articleData === null ? (
        <div></div>
      ) : (
        <>
          <div className={styles.header}>
            <h1>{articleData.title || ""}</h1>
            <img src={logo} alt="" onClick={gobackHome} />
          </div>
          <div className={styles.content}>
            <div className={styles.text}>
              <div className={styles.textPart}>
                {/* 使用marked库将markdown转换为HTML */}
                <div
                  className={styles.markdownContent}
                  dangerouslySetInnerHTML={{
                    __html: marked(articleData.content || ""),
                  }}
                />
              </div>
              <div className={styles.outline}>
                <div className={styles.outlineContent}>
                  <div className={styles.outlineTitle}>大纲</div>
                  <ul>
                    {outline.length === 0 ? (
                      <li>未检测到大纲</li>
                    ) : (
                      outline.map((item, index) => (
                        <li key={index}>
                          <a
                            href={`#${item.id}`}
                            onClick={(e) => {
                              e.preventDefault()
                              scrollToAnchor(item.id)
                            }}>
                            {item.title}
                          </a>
                        </li>
                      ))
                    )}
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </>
      )}
    </article>
  )
}

export default Article
